<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 应用公共函数库文件

/**
 * 生成密码hash值
 * @param $password
 * @return string
 */
function yoshop_hash($password)
{
    return md5(md5($password) . 'yoshop_salt_SmTRx');
}

/**
 * 获取当前域名及根路径
 * @return string
 */
function base_url()
{
    $subDir = str_replace('\\', '/', dirname(request()->server('PHP_SELF')));
    return request()->scheme() . '://' . request()->host() . $subDir . ($subDir === '/' ? '' : '/');
}
/**
 * 驼峰命名转下划线命名
 * @param $str
 * @return string
 */
function toUnderScore($str)
{
    $dstr = preg_replace_callback('/([A-Z]+)/', function ($matchs) {
        return '_' . strtolower($matchs[0]);
    }, $str);
    return trim(preg_replace('/_{2,}/', '_', $dstr), '_');
}

if (!function_exists('array_column')) {
    /**
     * array_column 兼容低版本php
     * (PHP < 5.5.0)
     * @param $array
     * @param $columnKey
     * @param null $indexKey
     * @return array
     */
    function array_column($array, $columnKey, $indexKey = null)
    {
        $result = array();
        foreach ($array as $subArray) {
            if (is_null($indexKey) && array_key_exists($columnKey, $subArray)) {
                $result[] = is_object($subArray) ? $subArray->$columnKey : $subArray[$columnKey];
            } elseif (array_key_exists($indexKey, $subArray)) {
                if (is_null($columnKey)) {
                    $index = is_object($subArray) ? $subArray->$indexKey : $subArray[$indexKey];
                    $result[$index] = $subArray;
                } elseif (array_key_exists($columnKey, $subArray)) {
                    $index = is_object($subArray) ? $subArray->$indexKey : $subArray[$indexKey];
                    $result[$index] = is_object($subArray) ? $subArray->$columnKey : $subArray[$columnKey];
                }
            }
        }
        return $result;
    }
}

/**
 * 多维数组合并
 * @param $array1
 * @param $array2
 * @return array
 */
function array_merge_multiple($array1, $array2)
{
    $merge = $array1 + $array2;
    $data = [];
    foreach ($merge as $key => $val) {
        if (
            isset($array1[$key])
            && is_array($array1[$key])
            && isset($array2[$key])
            && is_array($array2[$key])
        ) {
            $data[$key] = array_merge_multiple($array1[$key], $array2[$key]);
        } else {
            $data[$key] = isset($array2[$key]) ? $array2[$key] : $array1[$key];
        }
    }
    return $data;
}

/**
 * 数据生成树
 */
function list_to_tree($list, $pk='id',$pid = 'parent_id',$child = '_child',$root=0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        $level = 0;
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
* 对查询结果集进行排序
* @access public
* @param array $list 查询结果
* @param string $field 排序的字段名
* @param array $sortby 排序类型
* asc正向排序 desc逆向排序 nat自然排序
* @return array
*/
function list_sort_by($list,$field, $sortby='asc') {
    if(is_array($list)){
        $refer = $resultSet = array();
        foreach ($list as $i => $data)
            $refer[$i] = &$data[$field];
        switch ($sortby) {
            case 'asc': // 正向排序
                 asort($refer);
                 break;
            case 'desc':// 逆向排序
                 arsort($refer);
                 break;
            case 'nat': // 自然排序
                 natcasesort($refer);
                 break;
        }
        foreach ( $refer as $key=> $val)
            $resultSet[] = &$list[$key];
        return $resultSet;
    }
    return false;
 }
/**
 * 下载远程图片
 * @param $url 远程图片地址
 * @param $timeout 超时
 * @return string 文件地址
 */
function httpdown($url = '', $timeout = 60){
    $relativeFile = 'uploads/' . date('Ymd') . '/' . md5($url) . '.jpg';//文件相对地址
    $filename = realpath(WEB_PATH) . '/' . $relativeFile;
    $path = dirname($filename);
    if ( ! is_dir($path) && ! mkdir($path, 0755, true)) {
        return false;
    }
    try{
        $fp = fopen($filename, 'w');
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_exec($ch);
        curl_close($ch);
        fclose($fp);
        return $relativeFile;
    }catch(\Exception $e){
        return false;
    }
}

/** 
 *  
 * @todo 截取中文字符串不乱码 
 * @param string $str 
 * @param int $start 
 * @param int $length 
 * @param string $charset 
 * @param string $suffix 
 */  
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {  
    if(function_exists("mb_substr"))  
        $slice = mb_substr($str, $start, $length, $charset);  
    elseif(function_exists('iconv_substr')) {  
        $slice = iconv_substr($str,$start,$length,$charset);  
    }else{  
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";  
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";  
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";  
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";  
        preg_match_all($re[$charset], $str, $match);  
        $slice = join("",array_slice($match[0], $start, $length));  
    }  
    return $suffix ? $slice.'...' : $slice;  
}

function isMobile(){ 
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])){
        return true;
    } 
    // 如果via信息含有wap则一定是移动设备
    if (isset ($_SERVER['HTTP_VIA'])){ 
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    } 
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT'])){
        $clientkeywords = array ('nokia',    'sony',    'ericsson',    'mot',    'samsung',    'htc',    'sgh',    'lg',    'sharp',    'sie-',    'philips',    'panasonic',    'alcatel',    'lenovo',    'iphone',    'ipod',    'blackberry',    'meizu',    'android',    'netfront',    'symbian',    'ucweb',    'windowsce',    'palm',    'operamini',    'operamobi',    'openwave',    'nexusone',    'cldc',    'midp',    'wap',    'mobile'    ); 
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))){
            return true;
        } 
    } 
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT'])){ 
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))){
            return true;
        } 
    } 
    return false;
}
function atagprint($innerhtml , $url ,  $opennew=false){
    $target = $opennew ? 'target="_blank"' : '';
    echo '<a href="'.$url.'" '.$target.'>'.$innerhtml.'</a> ';
}
function atagsprint($list = []){
    $atags = '';
    foreach($list as $item){
        $atags .= atagprint($item[0] , $item[1] , $item[2]);
    }
    echo $atags;
}

if(!function_exists('_db')){
    // function _db($table , $arr=[] , $tf=false){
    //     $pre = 'mf_';
    //     $table = $pre . $table;
    //     return Db::connect('mysql://www_360bn_com:KDX2KXARAnrPKMHj@127.0.0.1:3306/www_360bn_com#utf8')->name($table);
    // }
}